package com.archie.xunji.huodong.fragments;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.archie.xunji.R;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.archie.xunji.huodong.adapters.ListView_HuodongAdapter;
import com.archie.xunji.huodong.entity.HotAndNewData;
import com.archie.xunji.huodong.widgets.TopView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HuodongFragment extends Fragment implements View.OnClickListener {

    private String path="http://service.xunjimap.com/xunjiservice/subject/list?4FDE7C501BEF041F45FE561412CD2251";

    private PullToRefreshListView listView;
    private List<String> head;
    private List<HotAndNewData>hotDatas,newDatas;
    private ListView_HuodongAdapter hotAdapter,newAdapter;
    private TopView topView;
    private LinearLayout linear_zuire,linear_zuixin;
    private TextView tv_zuire,tv_zuixin;
    private View line_zuire,line_zuixin;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        head=new ArrayList<String>();
        hotDatas=new ArrayList<HotAndNewData>();
        newDatas=new ArrayList<HotAndNewData>();
        hotAdapter=new ListView_HuodongAdapter(getActivity(),hotDatas);
        newAdapter=new ListView_HuodongAdapter(getActivity(),newDatas);
        topView=new TopView(getActivity());


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragment_huodong, container, false);
        listView= (PullToRefreshListView) v.findViewById(R.id.listView_huodongfragment);


      View  linearLayout= inflater.inflate(R.layout.adapterselect,null,false);
        linear_zuire= (LinearLayout) linearLayout.findViewById(R.id.linear_zuire_huodongfragment);
        linear_zuixin= (LinearLayout) linearLayout.findViewById(R.id.linear_zuixin_huodongfragment);

        line_zuire=linearLayout.findViewById(R.id.line_zuire);
        line_zuixin=linearLayout.findViewById(R.id.line_zuixin);
        tv_zuire= (TextView) linearLayout.findViewById(R.id.tv_zuire_huodongfragment);
        tv_zuixin= (TextView) linearLayout.findViewById(R.id.tv_zuixin_huodongfragment);
        linear_zuire.setOnClickListener(this);
        linear_zuixin.setOnClickListener(this);



        listView.getRefreshableView().addHeaderView(topView);
        listView.getRefreshableView().addHeaderView(linearLayout);
        listView.setAdapter(hotAdapter);
        initPTR();
        setPullDownLayout();

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        postrequest(path);


    }

    private void postrequest(String path) {
        RequestParams params = new RequestParams();
        // params.addHeader("name", "value");
        //  params.addQueryStringParameter("name", "value");

        params.addBodyParameter("userinfoid", "-1");
        params.addBodyParameter("appuserid", "43528");
        params.addBodyParameter("t", "20151112095750");
        params.addBodyParameter("token", "A90F61D07961FEC8A3FE3612E03E46AE62E75D16");
        params.addBodyParameter("sid", "lIKlUeaZSA");
        params.addBodyParameter("imei", "11E900F06307A0FCC18DB9A1E1FF3293");
        params.addBodyParameter("os", "Android+4.3");
        params.addBodyParameter("key", "WANDOUJIA");

// 只包含字符串参数时默认使用BodyParamsEntity，
// 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
        //  params.addBodyParameter("name", "value");

// 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
// 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
// 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
// MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
// 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
        //   params.addBodyParameter("file", new File("path"));

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                path,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        // testTextView.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            //  testTextView.setText("upload: " + current + "/" + total);
                        } else {
                            // testTextView.setText("reply: " + current + "/" + total);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        listView.onRefreshComplete();//-------------停止刷新
                        JSONObject json= null;
                        try {
                            json = new JSONObject(responseInfo.result);
                            JSONObject obj=json.getJSONObject("result");
                        //-------------解析头布局的图片
                            JSONArray subarray=obj.getJSONArray("subjectbannerlist");
                            List<String>headfu=new ArrayList<String>();
                            for (int i = 0; i <subarray.length() ; i++) {
                                JSONObject subObj=subarray.getJSONObject(i);
                                headfu.add(subObj.getString("imageurl"));
                            }


                            if(head.size()==0){
                                head.addAll(headfu);
                                topView.setData(head);
                            }

                            //--------------解析最热列表
                        JSONArray hotArray=obj.getJSONArray("hottestlist");
                            List<HotAndNewData>lists=new ArrayList<HotAndNewData>();
                            for (int i = 0; i <hotArray.length(); i++) {
                                JSONObject hotObj=hotArray.getJSONObject(i);
                                HotAndNewData hotData=new HotAndNewData();
                                hotData.parseJSON(hotObj);
                                lists.add(hotData);
                            }
                            hotDatas.clear();
                            hotDatas.addAll(lists);
                            hotAdapter.notifyDataSetChanged();
                            //-------------解析最新列表
                            JSONArray newArray=obj.getJSONArray("newestlist");
                            List<HotAndNewData>lists2=new ArrayList<HotAndNewData>();
                            for (int i = 0; i <newArray.length(); i++) {
                                JSONObject newObj=newArray.getJSONObject(i);
                                HotAndNewData newData=new HotAndNewData();
                                newData.parseJSON(newObj);
                                lists2.add(newData);
                            }
                            newDatas.clear();
                            newDatas.addAll(lists2);
                            newAdapter.notifyDataSetChanged();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    /*    List<GuangchangData> list=new ArrayList<GuangchangData>();
                        JSONObject json= null;
                        try {
                            json = new JSONObject(responseInfo.result);
                            JSONObject obj=json.getJSONObject("result");
                            JSONArray array=obj.getJSONArray("data");
                            for(int i=0;i<array.length();i++){
                                GuangchangData data=new GuangchangData();
                                data.parseJSON(array.getJSONObject(i));
                                list.add(data);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }*/

                      //  Log.d("huo", responseInfo.result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        //  testTextView.setText(error.getExceptionCode() + ":" + msg);
                    }
                });


    }


    //----------初始化pulltorefreshlistView的样式
    private void initPTR() {
        listView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);//只允许下拉刷新
        listView.setOnRefreshListener( new PullToRefreshBase.OnRefreshListener2<ListView>() {



            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                   postrequest(path);

            }
            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                listView.onRefreshComplete();
            }



        });

    }

    private void setPullDownLayout() {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        //获取下啦布局
        ILoadingLayout proxy=listView.getLoadingLayoutProxy(true,false);
        proxy.setPullLabel("下拉刷新");
        proxy.setReleaseLabel("放开以刷新。。。");
        proxy.setRefreshingLabel("玩命刷新。。。");
        proxy.setLastUpdatedLabel("最后刷新时间："+format.format(new Date()));
        //设置上啦加载的布局
        /*ILoadingLayout proxy2=listView.getLoadingLayoutProxy(false,true);
        proxy2.setPullLabel("请上拉加载");
        proxy2.setReleaseLabel("放开以加载。。。");
        proxy2.setRefreshingLabel("玩命加载。。。");
        proxy2.setLastUpdatedLabel("最后加载时间："+format.format(new Date()));*/
    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.linear_zuire_huodongfragment:

                 tv_zuire.setTextColor(Color.BLUE);
                line_zuire.setBackgroundColor(Color.BLUE);
                tv_zuixin.setTextColor(Color.BLACK);
                line_zuixin.setBackgroundColor(Color.parseColor("#42050206"));

                listView.setAdapter(hotAdapter);//-------------------------此处更新适配器一定要在最后更新否则前边的ui操作无效
                break;
            case R.id.linear_zuixin_huodongfragment:

                tv_zuire.setTextColor(Color.BLACK);
                line_zuire.setBackgroundColor(Color.parseColor("#42050206"));
                tv_zuixin.setTextColor(Color.BLUE);
                line_zuixin.setBackgroundColor(Color.BLUE);

                listView.setAdapter(newAdapter);//-------------------------此处更新适配器一定要在最后更新否则前边的ui操作无效
                break;
        }
    }
}
